package router

import (
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools/token"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

// 处理全局错误的
func MiddlewareErrorHandler(r *ghttp.Request) {
	r.Response.CORSDefault()
	logger.Async().Cat("router").Debug("路由：" + r.Request.URL.Path)
	logger.Async().Cat("router").Debug("Query：" + r.Request.URL.RawQuery)
	logger.Async().Cat("router").Debug("body：\n" + r.GetBodyString())
	r.Middleware.Next()
	//fmt.Println(r)

	if err := r.GetError(); err != nil {
		// 记录到自定义错误日志文件
		g.Log("exception").Error(err)
		//返回固定的友好信息
		r.Response.ClearBuffer()
		response.JsonExit(r, 1, err.Error())
	}
}

// 会员登录 中间件
func MiddlewareIsMemberLogin(r *ghttp.Request) {
	if token.CheckToken(r) {
		// 检测权限
		MiddlewareMemberPermissions(r)
	} else {
		r.Response.ClearBuffer()
		response.JsonExit(r, 10003, "请登录后继续操作")
		return
	}
}

func MiddlewareIsMemberLoginNoCheck(r *ghttp.Request) {
	token.CheckToken(r)
	r.Middleware.Next()
}

// 会员权限 中间件
func MiddlewareMemberPermissions(r *ghttp.Request) {
	if token.CheckPermissions(r) {
		r.Middleware.Next()
	} else {
		r.Response.ClearBuffer()
		response.JsonExit(r, 1, "没有操作权限")
		return
	}
}
